package com.maple.exclusivesport;

import android.content.Context;
import android.speech.tts.TextToSpeech;

import java.util.Locale;

/**
 * Created by maple on 2019/10/15 17:13
 * E-Mail Address：740917401@qq.com
 */
public class TTSUtils {
    Context context;

    private volatile static TTSUtils singleton;
    private TTSUtils(Context context){
        if(context!=null){
            context=context.getApplicationContext();
            tts = new TextToSpeech(context,new listener());
        }

    }
    public static TTSUtils getSingleton(Context context) {
        if (singleton == null) {
            synchronized (TTSUtils.class) {
                if (singleton == null) {
                    singleton = new TTSUtils(context);
                }
            }
        }

        return singleton;
    }

    public TextToSpeech tts;
    public class listener implements TextToSpeech.OnInitListener {

        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                //设置播放语言
                int result = tts.setLanguage(Locale.CHINESE);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    // Toast.makeText(BaseActivity.this, "不支持", Toast.LENGTH_SHORT).show();
                } else if (result == TextToSpeech.LANG_AVAILABLE) {
                    //初始化成功之后才可以播放文字
                    //否则会提示“speak failed: not bound to tts engine
                    //TextToSpeech.QUEUE_ADD会将加入队列的待播报文字按顺序播放
                    //TextToSpeech.QUEUE_FLUSH会替换原有文字
                    TTSUtils.getSingleton(context).tts.speak("欢迎参加掉肉肉计划，let go", TextToSpeech.QUEUE_ADD, null);
                }

            } else {
                android.util.Log.e("TAG", "初始化失败");
            }

        }


    }
    public void stopTTS() {
        if (tts != null) {
            tts.shutdown();
            tts.stop();
            tts = null;
        }
    }
}

